//
//  ImageViewController.m
//  SXH
//
//  Created by 龚啸 on 16/3/21.
//  Copyright © 2016年 lyss. All rights reserved.
//

#import "ImageViewController.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "EmptyView.h"
#import "CommonService.h"
#import "UserEntity.h"
#import "FindEntity.h"
#import "FindTableViewCell.h"
#import "LPUtils.h"
#import "ZanListViewController.h"
#import "FindMeViewController.h"
#import "ReportViewController.h"
#import "FindDetailViewController.h"
@interface ImageViewController ()<FindDelegate>{
    NSString* userId;
    int page;
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
}
@property (weak, nonatomic) IBOutlet UITableView *tabelViewList;
@property (nonatomic, strong) EmptyView *emptyView;
@property (nonatomic, strong) NSMutableArray *mutableArrayFindMe;
@property (nonatomic, strong) NSMutableArray *mutableArrayImageView;
@end

@implementation ImageViewController
@synthesize mutableArrayFindMe,mutableArrayImageView;
- (void)viewDidLoad {
    [super viewDidLoad];
    mutableArrayImageView = [[NSMutableArray alloc] init];
    mutableArrayFindMe = [[NSMutableArray alloc] init];
    userId= [UserEntity sharedInstance].userId;
    [self addHeader];
    [self addFooter];
}
- (void)addemptyViewToFront
{
    [self emptyViewinit];
    [self.tabelViewList addSubview:self.emptyView];
    [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tabelViewList.mas_top).offset(80);
        make.centerX.equalTo(self.tabelViewList.mas_centerX);
        make.width.equalTo(@320);
        make.height.equalTo(@100);
    }];
}

- (void)emptyViewinit
{
    if (self.emptyView == nil) {
        self.emptyView = [[EmptyView alloc]initWithFrame:CGRectMake(0, 0, 320, 100) andImagestr:@"nocontent" andTitle1:@"没有发表内容" andTitle2:@"去发现拍下你喜欢的一切与朋友分享"];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   
    if ([_tabelViewList.subviews containsObject:_emptyView]) {
                return 1;
            }

    return mutableArrayFindMe.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([_tabelViewList.subviews containsObject:_emptyView]) {
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"clearcell"];
        cell.frame = CGRectMake(0, 0, ScreenWidth, 300);
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell addSubview:_emptyView];
        [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.mas_top).offset(80);
            make.centerX.equalTo(cell.mas_centerX);
            make.width.equalTo(@320);
            make.height.equalTo(@100);
        }];
        return cell;
    }
    
    static NSString *couponTableViewCellIdentifier=@"FindTableViewCell";
    FindTableViewCell *cell = (FindTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FindTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        cell.delegate = self;
    }
    if ([mutableArrayFindMe count] < indexPath.row) {
        return cell;
    }
    FindEntity *entity = [mutableArrayFindMe objectAtIndex:indexPath.row];
    
    [cell setFindEntity:entity];
    cell.FirstImageView.tag = indexPath.row;
    [cell.viewBG.layer setMasksToBounds:YES];
    [cell.viewBG.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    [cell.viewBG.layer setBorderWidth:1.0]; //边框宽度
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0.77, 0.77, 0.77, 1 });
    [cell.viewBG.layer setBorderColor:colorref];//边框颜色
    
    cell.labelComment.text = entity.commentCount;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *insertTime = [dateFormatter dateFromString:entity.insert_time];
    NSString *time = [LPUtils compareCurrentTime:insertTime];
    cell.labelTimer.text = time;
    
    cell.labelTouristSpotName.text = entity.content;
    cell.labelTouristSpotName.numberOfLines=1;
    cell.labelTraveller.text = entity.nickname;
    [cell.btnZanTotal setTitle:entity.good forState:UIControlStateNormal];
    [cell.btnZanTotal.layer setMasksToBounds:YES];
    [cell.btnZanTotal.layer setCornerRadius:10.0]; //设置矩形四个圆角半径
    cell.btnZanTotal.tag = indexPath.row;
    
    [cell.btnAuthor sd_setImageWithURL:[NSURL URLWithString:entity.userAlbum] forState:UIControlStateNormal];
    [cell.btnAuthor.layer setMasksToBounds:YES];
    [cell.btnAuthor.layer setCornerRadius:20.0]; //设置矩形四个圆角半径
    cell.btnAuthor.tag = [entity.userid intValue];
    
    cell.btnShare.tag = indexPath.row;
    cell.btnZan.tag = indexPath.row;
    cell.btnReport.tag = indexPath.row;
    cell.btnAddGZ.tag = [entity.userid intValue];
    if ([entity.goodflag isEqualToString:@"1"] == YES) {
        [cell.btnZan setBackgroundImage:[UIImage imageNamed:@"发现_03_02"] forState:UIControlStateNormal];
        [cell.btnZanTitle setTitle:@"已赞" forState:UIControlStateNormal];
    } else {
        [cell.btnZan setBackgroundImage:[UIImage imageNamed:@"发现_03"] forState:UIControlStateNormal];
        [cell.btnZanTitle setTitle:@"赞" forState:UIControlStateNormal];
    }
    
    if ([[NSString stringWithFormat:@"%@",entity.followed]isEqualToString:@"1"]) {
        cell.btnAddGZ.hidden = YES;
        cell.labelTimer.hidden = NO;
    } else {
        cell.btnAddGZ.hidden = YES;
        cell.labelTimer.hidden = NO;
    }
    
    NSArray *arrayBtn = [[NSArray alloc] initWithObjects:cell.btnZan1,cell.btnZan2,cell.btnZan3,cell.btnZan4,cell.btnZan5,cell.btnZan6,nil];
    for (int i = 0; i < [entity.mutableArrayUser count] && i < 6; i++) {
        UserEntity *userEntity = [entity.mutableArrayUser objectAtIndex:i];
        UIButton *btn = arrayBtn[i];
        btn.hidden = NO;
        btn.tag = [userEntity.userId intValue];
        [btn sd_setImageWithURL:[NSURL URLWithString:userEntity.userAlbum] forState:UIControlStateNormal];
        [btn.layer setMasksToBounds:YES];
        [btn.layer setCornerRadius:17.0]; //设置矩形四个圆角半径
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self enterDetail:indexPath.row];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([mutableArrayFindMe count] < indexPath.row || mutableArrayFindMe.count == 0) {
        return 368;
    }
    FindEntity *entity = [mutableArrayFindMe objectAtIndex:indexPath.row];
    CGFloat height =  ((SCREEN_WIDTH - 8)* [entity.img_height floatValue])/[entity.img_width floatValue] + 160 + 20;
    if (entity.img_height == nil || entity.img_width == nil) {
        return 368;
    }
    
    return height;
}
- (void)addFooter
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tabelViewList;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page;
        [self getFindData:page RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)addHeader
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tabelViewList;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        [self getFindData:1 RefreshView:refreshView];
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}
- (void) getFindData:(int) pageNo RefreshView:(MJRefreshBaseView *)refreshView {
    NSString *strPageNo = [NSString stringWithFormat:@"%d", pageNo];
   
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = nil;
    param = [NSDictionary dictionaryWithObjectsAndKeys:
             userId, @"userid",
             strPageNo, @"page",
             @"21", @"limit",
             nil];

    
    [service getNetWorkData:param
                       Path:USER_TRAVEL
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"rows"];
                      NSNumber *code = (NSNumber*)[dic objectForKey:@"code"];
                      
                      if([code intValue] == 0) {
                          if (pageNo == 1)
                          {
                              [mutableArrayFindMe removeAllObjects];
                          }
                          for (NSDictionary* attributes in array)
                          {
                              FindEntity *entity = [[FindEntity alloc] init];
                              entity = [entity initWithAttributes:attributes];
                              [mutableArrayFindMe addObject:entity];
                          }
                          if ([mutableArrayFindMe count] <= 0 ) {
                              [self addemptyViewToFront];
                          }
                          else
                          {
                              [self.emptyView removeFromSuperview];
                          }
                         
                          
                      }
                      else
                      {
                          [self addemptyViewToFront];
                          
                      }

                      [self doneWithView:refreshView];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self doneWithView:refreshView];
                  }];
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tabelViewList reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void) shareAction:(NSInteger)tag {
    
//    UIImageView *imageView = [mutableArrayImageView objectAtIndex:tag];
    
    FindEntity *entity = [mutableArrayFindMe objectAtIndex:tag];
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.delegate = self;
    HUD.labelText = Loading_Hard_Text;
    
    NSArray* imageArray = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"icon-05 3"], nil];
    
    [CommonService showShareActionSheet:self.view HUD:HUD
                             ImageArray:imageArray
                                    URL:PORTAL_URL
                                  Title:@"美图分享"
                                Content:entity.content];
}

- (void) zanAction:(NSInteger)tag {
    
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    
    
    FindEntity *entity = [mutableArrayFindMe objectAtIndex:tag];
    
    
    [super showLoadingView:YES];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           entity.ID, @"travel_id",
                           userEntity.userId, @"userid", nil];
    
    [service getNetWorkData:param
                       Path:USER_TRAVEL_GOOD
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      /*
                       code	返回码 0 有数据返回 1 无数据返回
                       flag	点赞标识 1 点赞 2 未点赞
                       success	操作是否成功 返回 true false
                       msg	返回消息内容
                       */
//                      [mutableArrayFindMe removeAllObjects];
                      [self getFindData:page RefreshView:nil];
                      [super showLoadingView:NO];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [super showLoadingView:NO];
                      [self doneWithView:nil];
                  }];
}

/* server will return the image width and hegiht, so this function will no use.
 
 -(void) lk_finishDownLoad:(UIImage*)image {
 DebugLog(@"imageView = %f, %f", image.size.width, image.size.height);
 }
 */

- (void) enterZanListVC:(NSInteger)tag {
    FindEntity *entity = [mutableArrayFindMe objectAtIndex:tag];
    ZanListViewController *vc = [[ZanListViewController alloc] init];
    vc.findEntity = entity;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void) enterUserProfileVC:(NSInteger)tag {
    FindMeViewController *vc = [[FindMeViewController alloc] init];
    vc.userId = [NSString stringWithFormat:@"%d", (int)tag];
    
        [self.navigationController pushViewController:vc animated:YES];
   
}

- (void) enterReportVC:(NSInteger)tag
{
   
    FindEntity *entity = [mutableArrayFindMe objectAtIndex:tag];
    
    ReportViewController *vc = [[ReportViewController alloc] init];
    vc.userId = userId;
    vc.travel_id = entity.ID;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)clickAtImage:(UIImageView *)imageView
{
    [self enterDetail:imageView.tag];
}
- (void)guanzhuAction:(NSInteger)tag
{
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           [NSString stringWithFormat:@"%d", (int)tag],@"attention_id",
                           userId,@"userid",
                           nil];
    
    [service getNetWorkData:param
                       Path:USER_ATTENTION
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSNumber *code = [dic objectForKey:@"code"];
                      if ([code intValue] == 0) {
                          ALERT_ERR_MSG(@"关注成功");
                          [mutableArrayFindMe removeAllObjects];
                          [self getFindData:1 RefreshView:nil];
                      } else {
                          ALERT_ERR_MSG(@"关注失败");
                      }
                  } Failed:^(NSInteger errorCode, NSString *message) {
                  }];
}

-(void)enterDetail:(NSInteger)index
{
    FindEntity *entity = [mutableArrayFindMe objectAtIndex:index];
    FindDetailViewController *vc = [[FindDetailViewController alloc] init];
    vc.findEntity = entity;
    
    [self.navigationController pushViewController:vc animated:YES];
}

@end
